import axios from 'axios'
import request from '@/config/request'
import { generateEnglishQuestions } from '@/utils/question'
import { getAllSubjectApi, getSelfModuleSubjectApi } from '@/api/common'

// 获得已有作业科目列表
export const getStudentExamSubjectApi = (data) => {
  return new Promise((resolve) => {
    Promise.all([
      getAllSubjectApi({
        formatter: (subjects) => {
          return subjects.map((item) => {
            return {
              gradeId: null,
              gradeName: null,
              stageId: null,
              stageName: null,
              subjectId: item.value,
              subjectName: item.label
            }
          })
        }
      }),
      getSelfModuleSubjectApi()
    ]).then((res) => {
      const [subjectIdListData, moduleSubjectListData] = res
      const { data: subjectIdList } = subjectIdListData
      const { data: moduleSubjectList } = moduleSubjectListData

      // 获取已经开通的科目
      if (Array.isArray(moduleSubjectList) && moduleSubjectList.length > 0) {
        const selfSubjectList = moduleSubjectList.filter((i) => i.moduleId === '5')
        if (Array.isArray(subjectIdList) && selfSubjectList.length > 0) {
          const copySubjectIdList = JSON.parse(JSON.stringify(subjectIdList))
          const selfSubjectIds = selfSubjectList.map((i) => i.subject)
          subjectIdList.splice(0, subjectIdList.length)
          subjectIdList.push(
            ...copySubjectIdList.filter((i) => selfSubjectIds.includes(i.subjectId))
          )
        } else {
          subjectIdList.splice(0, subjectIdList.length)
        }
      } else {
        subjectIdList.splice(0, subjectIdList.length)
      }

      resolve(subjectIdListData)
    })
  })
}

// 获取学生作业列表
export const getStudentExamByUpScoreListApi = (data) => {
  return request.get('/app-api/exam/app/exam/getExamPageByUpScore', data)
}

// 获取问题
export const getQuestionsApi = (url, params = {}) => {
  const { subjectId } = params

  return new Promise(async (resolve) => {
    const { data: _data = {} } = await axios.get(url)
    let data = [] // 题目列表

    // 分类并生成题目列表
    if (_data.questions) {
      if (subjectId == '66') {
        data = generateEnglishQuestions(_data) // 英语听说
      } else {
        data = _data.questions // 学科网、教辅题库、菁优网等题目
      }
    } else {
      data = _data // 学科网、教辅题库、菁优网等题目（兼容旧的）
    }

    // 题目序号从低到高排序
    const pageGroups = data.reduce((groups, question) => {
      const key = question.pageIndex

      if (!groups[key]) {
        groups[key] = []
      }

      groups[key].push(question)

      return groups
    }, {})
    const questionsSortByAsc = []
    for (let pageIndex in pageGroups) {
      const child_questions = pageGroups[pageIndex]
      questionsSortByAsc.push(
        ...child_questions.sort(function (a, b) {
          return parseInt(a.questionIndex) - parseInt(b.questionIndex)
        })
      )
    }

    resolve(questionsSortByAsc)
  })
}

// 按班级获取学生列表
export const getStudentByClassApi = (data) => {
  return request.get('/app-api/exam/exam-data-entry/studentByClass', data)
}

// 按分组获取学生列表
export const getStudentByGroupApi = (data) => {
  return request.get('/app-api/exam/exam-data-entry/studentByGroup', data)
}

// 提交分数批量
export const upExamQuestionScoreListApi = (data) => {
  return request.post('/app-api/exam/app/exam/upExamQuestionScoreList', data)
}

// 获得考试学生题目作答情况
export const getExamStudentQuestions = (data) => {
  return request.post('/app-api/exam/app/exam/getExamStudentQuestions', data)
}
